/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.esdc.librarysystem.manager;

import com.esdc.librarysystem.exception.LibraryPolicyException;
import com.esdc.librarysystem.entity.ContactEntity;
import com.esdc.librarysystem.entity.MemberEntity;
import com.esdc.librarysystem.exception.NotExistException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author shou1dwe
 */
@Stateful
public class MemberManagerBean implements MemberManagerRemote {
    @PersistenceContext
    EntityManager em;

    MemberEntity member;
    ContactEntity contact;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public long addMember (String name, String type, String password, String department, String email, String faculty, String telNumber) {
        member = new MemberEntity();
        member.create(name, type, password);

        contact = new ContactEntity();
        contact.create(department, faculty, email, telNumber);

        member.setContact(contact);
        
        em.persist(member);
        return member.getId();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void deleteMember (long id) throws NotExistException, LibraryPolicyException{
        member = em.find(MemberEntity.class, id);
        if(member == null){
            throw new NotExistException("Member not exists.");
        }

        if(member.getBooks().size()!=0){
            throw new LibraryPolicyException("Outstanding loan exists.");
        }

        em.remove(member);
    }

    public boolean verify(long memberId, String password) {
        member = em.find(MemberEntity.class, memberId);
        try{
            if(member.getPassword().equals(password)){
                System.out.println(String.format("User '%s' verified", member.getName()));
                return true;
            }
        } catch(NullPointerException npe){
            
        }
        System.out.println(String.format("User not verified"));
        return false;
    }

    public List findMembersByName(String name){
        return new ArrayList();
    }

}
